package yxy.game.pm2.command.player;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankWorship;
import yxy.game.pm2.bean.module.rank.RankWorshipPlayer;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlayerMessage;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.player.RankPlayerPower;

import java.util.Collection;

/** 布阵 战力排行榜 */
@MessageType(proto = Command.PowerRank, classtype = PlayerMessage.PowerRankRequest.class)
public class CMD_PowerRank extends Command<PlayerMessage.PowerRankRequest> {

	@Override
	public void execute(MessageSource messageSource, PlayerMessage.PowerRankRequest request) {
		String playerCode = messageSource.getTag();

		PlayerMessage.PowerRankResponse.Builder response = PlayerMessage.PowerRankResponse.newBuilder();

		RankPlayerPower rankPlayerPower = RankPlayerPower.getRank(playerCode);
		try {
			RankWorship worship = rankPlayerPower.getWorship();
			RankWorshipPlayer worshipPlayer = RankWorshipPlayer.get(playerCode, worship);

			Collection<RankEntry> top = rankPlayerPower.top(rankPlayerPower.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int power = entry.getValue().intValue();

				PlayerMessage.RankPower.Builder builder = PlayerMessage.RankPower.newBuilder();
				builder.setRank(++rank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(pCode));
				builder.setPower(power);
				builder.setFans(worship.getScore(pCode));
				builder.setLiked(worshipPlayer.getWorshiped().contains(pCode));
				response.addRank(builder);
			}

			{
				int playerRank = 0;
				long power = 0;
				RankEntry entry = rankPlayerPower.get(playerCode);
				if (entry != null) {
					playerRank = rankPlayerPower.rank(playerCode);
					power = entry.getValue();
				}

				PlayerMessage.RankPower.Builder builder = PlayerMessage.RankPower.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(new PlayerHandle().playerSimpleInfo(playerCode));
				builder.setPower(power);
				response.setMy(builder);
			}

			response.setTimes(worshipPlayer.remainTimes());

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, PlayerMessage.PowerRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}